package com.carrod.client.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClinet implements Runnable {

	private static SocketClinet clinet = null;
	private DataOutputStream out = null;
	private DataInputStream in = null;
	private String ipAddress = "";
	private String userName = "";
		
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	private int port = 0;
	private Socket socket;

	public Socket getSocket() {
		return socket;
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public void setIpAddress(String ipAddress) {
		this.ipAddress = ipAddress;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public DataOutputStream getOut() {
		return out;
	}

	private SocketClinet() {

	}

	public static SocketClinet getInstance() {
		if (clinet == null) {
			clinet = new SocketClinet();
			return clinet;
		}
		return clinet;
	}

	public void sendMessage(String message) {
		try {
			out = new DataOutputStream(getSocket().getOutputStream());
			out.writeUTF(message);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String reciveMessage() {
		try {
			in = new DataInputStream(socket.getInputStream());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String msg;
		try {
			msg = in.readUTF();
			return msg;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public Socket linkToChatServer() {

		try {
			socket = new Socket(getIpAddress(), getPort());
			return socket;

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;

	}

	@Override
	public void run() {
		linkToChatServer();

	}

}
